<?php

namespace App\Admin\Controllers;

use Encore\Admin\Form;
use App\Models\Product;
use Encore\Admin\Layout\Content;
use Encore\Admin\Controllers\AdminController;

class ProductSlidesController extends AdminController
{
    protected $title = '商品轮播图';
	
	protected function product($id = null)
	{
		$productId = $id ?? request('product_id');
		if (!$product = Product::find($productId)) {
			return back()->with(admin_error('必须依附于商品主体'));
		}
		return $product;
	}
	
	public function edit($id, Content $content)
	{
		return $content
			->title($this->title())
			->description($this->description['edit'] ?? trans('admin.edit'))
			->body($this->form($id)->edit($id));
	}
    
    protected function form($id = null)
    {
        $form = new Form(new Product());
	
	    $product = $this->product($id);
	
	    $form->hasMany('slides', "商品：{$product->title}", function (Form\NestedForm $form) {
		    $form->image('slide', 'IMG')->uniqueName()->help('NOTE：保证清晰的前提下尽可能压缩体积');
		    $form->text('brief', '摘要');
	    });
	    
	    $this->formTools($form);
	    $this->formFooter($form);
	    $this->formSaved($form);
	
	    $form->setAction("/admin/product-slides/{$id}?product_id={$id}");

        return $form;
    }
	
	protected function formTools(Form $form)
	{
		$form->tools(function (Form\Tools $tools) {
			$tools->disableList();
			$tools->disableView();
			$tools->disableDelete();
			$tools->prepend('
		        <a
                    href="'.route('admin.products.index').'"
                    class="btn btn-sm btn-default" style="margin-right: 5px">
                    <i class="fa fa-list"></i> 列表
                </a>
	        ');
		});
	}
	
	protected function formFooter(Form $form)
	{
		$form->footer(function (Form\Footer $footer) {
			$footer->disableViewCheck();
			$footer->disableCreatingCheck();
			$footer->disableEditingCheck();
		});
	}
	
	protected function formSaved(Form $form)
	{
		$form->saved(function () {
			return redirect(route('admin.products.index'));
		});
	}
}
